package db_main

import (
	"gorm.io/gorm"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/db/mysql/models/models_main"
)

const (
	totalRecommendUserField  = "total_recommend" // 推荐总数
	totalRecommendNobleField = "total_noble"     // 推荐贵族总数
)

const (
	ReferTypeRegister = "origin_anchor_id"       //来源直播间注册
	ReferTypeNoble    = "origin_noble_anchor_id" //来源直播间贵族
)

func initUserRecommend(userId, originAnchorId, originNobleAnchorId int64) bool {
	recommend := models_main.UserRecommend{
		UserId:              userId,
		OriginAnchorId:      originAnchorId,
		TotalRecommend:      0,
		OriginNobleAnchorId: originNobleAnchorId,
		TotalNoble:          0,
	}
	err := global2.GetX().Model(&recommend).Create(recommend).Error
	if err != nil {
		return false
	}
	return true
}

func updateUserRecommend(userId, referUserId int64, referType string) bool {
	recommend := models_main.UserRecommend{}
	err := global2.GetX().Model(&recommend).Where("user_id", userId).Update(referType, referUserId).Error
	if err != nil {
		return false
	}
	return true
}
func findByUserRecommend(userId int64) *models_main.UserRecommend {
	recommend := models_main.UserRecommend{}
	err := global2.GetR().Where("user_id", userId).Limit(1).Take(&recommend).Error
	if err != nil {
		return nil
	}
	return &recommend
}

func SetUserRecommendInc(userId, referUserid int64) {
	recommend := findByUserRecommend(userId)
	// 用户没推荐过
	if recommend == nil {
		initUserRecommend(userId, referUserid, 0)
	} else {
		if recommend.OriginAnchorId == 0 {
			updateUserRecommend(userId, referUserid, ReferTypeRegister)
		}
	}
	if recommend == nil {
		incUserRecommendField(referUserid, totalRecommendUserField)
	} else {
		if recommend.OriginAnchorId == 0 {
			incUserRecommendField(referUserid, totalRecommendUserField)
		}
	}

}

func SetUserRecommendNobleInc(userId, referUserid int64) {
	recommend := findByUserRecommend(userId)
	if recommend == nil {
		initUserRecommend(userId, 0, referUserid)
	} else {
		if recommend.OriginNobleAnchorId == 0 {
			updateUserRecommend(userId, referUserid, ReferTypeNoble)
		}

	}

	if recommend == nil {
		incUserRecommendField(referUserid, totalRecommendNobleField)
	} else {
		if recommend.OriginNobleAnchorId == 0 {
			incUserRecommendField(referUserid, totalRecommendNobleField)
		}
	}
}

func incUserRecommendField(userId int64, field string) {

	// 查询推荐人
	recommend := findByUserRecommend(userId)
	if recommend == nil {
		// 推荐人没有推荐记录，初始化
		initUserRecommend(userId, 0, 0)
	}

	model := models_main.UserRecommend{}
	err := global2.GetX().Model(&model).Where("user_id", userId).
		UpdateColumn(field, gorm.Expr(field+" + ?", 1)).Error
	if err != nil {
		global2.Log.Errorf("record incr total_recommend err: %v", err)
		return
	}
}
